package de.ts.database;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;

import de.ts.fremdsprache.User;

public class DAO {

	Database database;

	/**
	 * Creates a new instance of this object, create a new databse object, build
	 * up a connection to the database and crate a table for the entries if it
	 * doesn't exist.
	 * 
	 * @param filename
	 *            URL of the SQLite-Database
	 * @throws DAOException
	 */
	public DAO(String filename) throws DAOException {
		database = new Database(filename);
		try {
			database.connect();
			database.createTable();
		} catch (Exception e) {
			throw new DAOException(e);
		}
	}

	/**
	 * Returns the count of entries by using "countEntries()" from Database.
	 * 
	 * @return count of entries
	 * @throws SQLException
	 */
	public int countEntries() throws DAOException {
		try {
			return database.countEntries();
		} catch (SQLException e) {
			throw new DAOException(e);
		}
	}
	
	public void insertUser(User user) throws DAOException {
		try {
			database.insertUser(user);
		} catch (SQLException e) {
			throw new DAOException(e);
		}
	}

	/**
	 * Returns a whole by index specific entry from the database by using
	 * "getEntry" from Database.
	 * 
	 * @param number
	 *            Index of the entry
	 * @return whole entry
	 * @throws SQLException
	 */
	public User getUser(int number) throws DAOException {
		try {
			return database.getEntry(number);
		} catch (SQLException e) {
			throw new DAOException(e);
		}
	}
	
	public List<User> getUsers() throws DAOException {
		try {
			ArrayList<User> entries = new ArrayList<>();
			for(int i = 0; i < database.countEntries(); i++) {
				entries.add(database.getEntry(i));
			}
			return entries;
		} catch (SQLException e) {
			throw new DAOException(e);
		}
	}
	public void disconnect() {
		database.disconnect();
	}
}
